package com.hjc.service.impl;

import com.hjc.entity.Product;
import com.hjc.entity.Result;
import com.hjc.mapper.ProductMapper;
import com.hjc.page.Page;
import com.hjc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;


    @Override
    public Page findAllProductList(Page page, Product product) {
        int rowCount = productMapper.selectAllProductCount(product);
        List<Product> productList = productMapper.selectAllProductList(page, product);
        page.setTotalNum(rowCount);
        page.setResultList(productList);
        return page;
    }

    @Value("${file.access-path}")
    private String accessPath;
    @Override
    public Result addProduct(Product product) {
        Product product1 = productMapper.selectProductByNum(product.getProductNum());
        if (product1 != null) {
            return Result.err(Result.CODE_ERR_BUSINESS,"改型号已经存在！");
        }
        product.setImgs(accessPath + product.getImgs());
        int flag = productMapper.insertProduct(product);
        if (flag > 0) {
            return Result.ok("添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"添加失败！");
    }

    @Override
    public Result setUpDownState(Integer productId, String upDownState) {
        int flag = productMapper.updateUpDownState(productId, upDownState);
        if(flag > 0) {
            return Result.ok("状态更新成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "状态更新失败！");
    }

    @Override
    public Result removeProductByProductId(Integer productId) {
        int flag = productMapper.deleteProductByProductId(productId);
        if (flag > 0) {
            return Result.ok("删除成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "删除失败！");
    }

    @Override
    public Result setProductById(Product product) {
        if (!product.getImgs().startsWith(accessPath)) {
            product.setImgs(accessPath + product.getImgs());
        }
        int flag = productMapper.updateProductById(product);
        if (flag > 0) {
            return Result.ok("修改商品信息成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "修改商品信息失败！");
    }
}
